package com.galaxy.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.galaxy.common.dao.BaseDaoI;
import com.galaxy.common.util.BeanUtils;
import com.galaxy.common.util.file.FileUtil;
import com.galaxy.common.web.page.Json;
import com.galaxy.system.entity.ActionEntity;
import com.galaxy.system.entity.ModuleEntity;
import com.galaxy.system.service.ModuleServiceI;
import com.galaxy.system.web.form.ActionForm;
import com.galaxy.system.web.form.ModuleForm;

@Service
@Transactional
public class ModuleServiceImpl implements ModuleServiceI {

	@Autowired
	private BaseDaoI<ModuleEntity> basedaoModule;
	
	@Autowired
	private BaseDaoI<ActionEntity> basedaoAction;
	
	@Override
	public Json save(ModuleForm form) {
		Json j = new Json();
		try {
			ModuleEntity entity = new ModuleEntity();
			BeanUtils.copyProperties(form, entity);
			
			if (null != form.getPid() && !"".equals(form.getPid())) {
				entity.setModule(this.basedaoModule.get(ModuleEntity.class, form.getPid()));
			}
			this.basedaoModule.save(entity);
			
			j.setMsg("创建成功！");
			j.setStatus(true);
		} catch (Exception e) {
			j.setMsg("创建失败！");
		}
		return j;
	}
	
	
	@Override
	public Json saveOrupdate(ModuleForm form) {
		Json j = new Json();
		try {
			ModuleEntity entity = new ModuleEntity();
			BeanUtils.copyProperties(form, entity);

			if (null != form.getPid() && !"".equals(form.getPid())) {
				entity.setModule(this.basedaoModule.get(ModuleEntity.class, form.getPid()));
			}
			this.basedaoModule.saveOrUpdate(entity);
			j.setMsg("创建成功！");
			j.setStatus(true);
		} catch (Exception e) {
			j.setMsg("创建失败！");
		}
		return j;
	}

	@Override
	public Json delete(String id) {
		Json j = new Json();
		try {
			ModuleEntity t = this.basedaoModule.get(ModuleEntity.class, id);
			del(t);
			j.setMsg("删除成功！");
			j.setStatus(true);
		} catch (Exception e) {
			j.setMsg("删除失败，该模块可能已分配给角色了，请先解除关联！");
		}
		return j;
	}

	private void del(ModuleEntity entity) {
		if (entity.getModules() != null && entity.getModules().size() > 0) {
			for (ModuleEntity e : entity.getModules()) {
				del(e);
			}
		}
		this.basedaoModule.delete(entity);
	}

	@Override
	public Json edit(ModuleForm form) {
		Json j = new Json();
		try {
			ModuleEntity entity = this.basedaoModule.get(ModuleEntity.class, form.getId());
			BeanUtils.copyProperties(form, entity);
			if (null != form.getPid() && !"".equals(form.getPid())) {
				
			}
			if (null != form.getPid() && !"".equals(form.getPid())) {
				if(!entity.getId().equals(form.getPid())) {
					entity.setModule(this.basedaoModule.get(ModuleEntity.class, form.getPid()));
				} else {
					j.setMsg("操作有误，父模块服务关联自己！");
					return j ;
				}
			}
			
			this.basedaoModule.update(entity);
			
			j.setMsg("编辑成功！");
			j.setStatus(true);
			
		} catch (Exception e) {
			e.printStackTrace();
			j.setMsg("编辑失败！");
		}
		return j;
	}

	@Override
	public Json ondrop(ModuleForm form) {
		Json j = new Json();
		try {
			ModuleEntity entity = this.basedaoModule.get(ModuleEntity.class, form.getId());

			ModuleEntity targetMenu = this.basedaoModule.get(ModuleEntity.class, form.getPid());

			if ("bottom".equalsIgnoreCase(form.getPoint()) || "top".equalsIgnoreCase(form.getPoint())) {
				ModuleEntity parentMenu = targetMenu.getModule();
				entity.setModule(parentMenu);
				if (null == parentMenu) {
					entity.setType("R");
				} else {
					entity.setType("F");
				}
				if ("bottom".equalsIgnoreCase(form.getPoint())) {
					entity.setSeq(targetMenu.getSeq() - 1);
				} else {
					entity.setSeq(targetMenu.getSeq() + 1);
				}
			} else {
				entity.setType("F");
				entity.setModule(targetMenu);
			}
			this.basedaoModule.update(entity);
			j.setMsg("节点移动成功！");
			j.setStatus(true);
		} catch (Exception e) {
			j.setMsg("节点移动失败！");
		}
		return j;
	}

	@Override
	public ModuleForm get(String id) {
		ModuleEntity entity = this.basedaoModule.get(ModuleEntity.class, id);
		ModuleForm form = new ModuleForm();
		BeanUtils.copyProperties(entity, form);
		if (null != entity.getModule()) {
			form.setPid(entity.getModule().getId());
		}
		return form;
	}

	@Override
	public List<ModuleForm> findMenusAll(ModuleForm form, boolean flag) {
		List<ModuleForm> forms = new ArrayList<ModuleForm>();

		String hql = "select t from ModuleEntity t where t.module is null and t.type='R' order by seq desc";
		List<ModuleEntity> menus = this.basedaoModule.find(hql);
		for (ModuleEntity entity : menus) {
			forms.add(recursiveNaviNode(entity, flag));
		}
		return forms;
	}

	public ModuleForm recursiveNaviNode(ModuleEntity me, boolean flag) {
		ModuleForm mf = new ModuleForm();
		BeanUtils.copyProperties(me, mf);
		mf.setText(me.getModuleName());

		Map<String, String> attributes = new HashMap<String, String>();
		attributes.put("href", me.getLinkUrl());
		mf.setAttributes(attributes);
		
		if (null != me.getModules() && me.getModules().size() > 0) {
			//mf.setState("closed") ;
			
			Set<ModuleEntity> rs = me.getModules();
			List<ModuleForm> children = new ArrayList<ModuleForm>();
			for (ModuleEntity entity : rs) {
				//如果是combox效果则不显示操作菜单
				if(flag) {
					if(!entity.getType().equals("O")) {
						ModuleForm tn = recursiveNaviNode(entity, flag);
						BeanUtils.copyProperties(entity, tn, new String[] { "state" });
						tn.setText(entity.getModuleName());
						children.add(tn);
					}
				} else {
					ModuleForm tn = recursiveNaviNode(entity, flag);
					BeanUtils.copyProperties(entity, tn, new String[] { "state" });
					tn.setText(entity.getModuleName());
					children.add(tn);
				}
				
			}
			
			mf.setChildren(children);
		}
		return mf;
	}

	@Override
	public void exportMenusAll(ServletContext sc) {
		List<ModuleForm> menu = new ArrayList<ModuleForm>();

		String hql = "select t from ModuleEntity t where t.module is null and t.type='R' order by seq desc";
		List<ModuleEntity> menus = this.basedaoModule.find(hql);
		for (ModuleEntity entity : menus) {
			ModuleForm mf = new ModuleForm();
			BeanUtils.copyProperties(entity, mf);
			mf.setText(entity.getModuleName());
			menu.add(mf);
			exportTree(entity.getModules(), entity, sc);
		}
		String path = sc.getRealPath("/resources/admin/") + "/nav-menu-data.json";
		FileUtil.outJson(path, "", menu);
	}

	public void exportTree(Set<ModuleEntity> menus, ModuleEntity m, ServletContext sc) {
		List<ModuleForm> forms = new ArrayList<ModuleForm>();
		if (null != menus && menus.size() > 0) {
			for (ModuleEntity entity : menus) {
				if (!"O".equals(entity.getType())) {
					forms.add(recursiveNaviNodeExport(entity));
				}
			}
		}
		String path = sc.getRealPath("/resources/admin/") + "/nav-" + m.getId() + "-menu-data.json";
		FileUtil.outJson(path, "", forms);
	}

	public ModuleForm recursiveNaviNodeExport(ModuleEntity me) {
		ModuleForm mf = new ModuleForm();
		BeanUtils.copyProperties(me, mf);
		mf.setText(me.getModuleName());

		Map<String, String> attributes = new HashMap<String, String>();
		attributes.put("href", me.getLinkUrl());
		mf.setAttributes(attributes);

		if (null != me.getModules() && me.getModules().size() > 0) {

			Set<ModuleEntity> rs = me.getModules();
			List<ModuleForm> children = new ArrayList<ModuleForm>();
			for (ModuleEntity entity : rs) {
				if (!"O".equals(entity.getType())) {
					ModuleForm tn = recursiveNaviNodeExport(entity);
					BeanUtils.copyProperties(entity, tn, new String[] { "state" });
					tn.setText(entity.getModuleName());
					children.add(tn);
				}
			}

			mf.setChildren(children);
		}
		return mf;
	}


	@Override
	public Json save_action(ActionForm form) {
		Json j = new Json() ;
		
		ActionEntity entity = new ActionEntity() ;
		BeanUtils.copyProperties(form, entity) ;
		
		this.basedaoAction.save(entity) ;
		j.setStatus(true) ;
		j.setMsg("添加成功！") ;
		
		return j;
	}


	@Override
	public ActionForm get_action(ActionForm form) {
		ActionEntity entity = this.basedaoAction.get(ActionEntity.class, form.getId()) ;
		BeanUtils.copyProperties(entity, form) ;
		return form ;
	}


	@Override
	public Json delete_action(ActionForm form) {
		Json j = new Json() ;
		this.basedaoAction.delete(this.basedaoAction.get(ActionEntity.class, form.getId())) ;
		j.setStatus(true) ;
		j.setMsg("删除成功！") ;
		return j;
	}


	@Override
	public Json edit_action(ActionForm form) {
		Json j = new Json() ;
		ActionEntity entity = this.basedaoAction.get(ActionEntity.class, form.getId()) ;
		BeanUtils.copyProperties(form, entity) ;
		j.setStatus(true) ;
		j.setMsg("删除成功！") ;
		return j;
	}


	@Override
	public List<ActionForm> view_action(ActionForm form) {
		
		List<ActionForm> list = new ArrayList<ActionForm>() ;
		
		List<ActionEntity> entitys = this.basedaoAction.find("select t from ActionEntity t order by id") ;
		for (ActionEntity entity : entitys) {
			ActionForm af = new ActionForm() ;
			BeanUtils.copyProperties(entity, af) ;
			list.add(af) ;
		}
		return list;
	}

}
